package com.cci.kangdao.task;

import com.cci.kangdao.dao.WeChatGetMaterialDao;
import com.cci.kangdao.dao.model.AccessToken;
import com.cci.kangdao.redis.RedisClientUtils;
import com.cci.kangdao.utilTool.*;
import net.sf.json.JSONObject;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.cci.kangdao.utilTool.WeiXinUtil.doGetStr;


@Component
public class SynchronizationWeChatDataTask {
	private Logger log = Logger.getLogger(this.getClass().getName());
	//获取素材voice_count(语音总数量),video_count(视频总数量),image_count(图片总数量),news_count	(图文总数量)的url
	private static final String MATERIAL_COUNT = "https://api.weixin.qq.com/cgi-bin/material/get_materialcount?access_token=ACCESS_TOKEN";
	//获取素材列表url
	private static final String MATERIAL_List="https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token=ACCESS_TOKEN";
	@Autowired
	private RedisClientUtils redisClientUtils;
	@Autowired
	private WeChatGetMaterialDao weChatGetMaterialDao;


	//每天每隔一小时同步微信数据到数据库
    public void synchronizationWeChatData(){
		try{
			log.info("定时任务开始----获取微信公众号文章保存数据库");
			for(int i=1;i<=7;i++) {
                String appid = "";
                String appsecret = "";
                String token = "";
                if (i == 1) {  //CCI
                    appid = PropertiesUtil.getProperties("projectconfig.properties", "CCIAPPID");
                    appsecret = PropertiesUtil.getProperties("projectconfig.properties", "CCIAPPSECRET");
                } else if (i == 2) {  //BFCEC
                    appid = PropertiesUtil.getProperties("projectconfig.properties", "BFCECAPPID");
                    appsecret = PropertiesUtil.getProperties("projectconfig.properties", "BFCECAPPSECRET");
                } else if (i == 3) {  //DCEC
                    appid = PropertiesUtil.getProperties("projectconfig.properties", "DCECAPPID");
                    appsecret = PropertiesUtil.getProperties("projectconfig.properties", "DCECAPPSECRET");
                } else if (i == 4) {  //XCEC
                    appid = PropertiesUtil.getProperties("projectconfig.properties", "XCECAPPID");
                    appsecret = PropertiesUtil.getProperties("projectconfig.properties", "XCECAPPSECRET");
                } else if (i == 5) {  //GCIC  广西康明斯
                    appid = PropertiesUtil.getProperties("projectconfig.properties", "GCICAPPID");
                    appsecret = PropertiesUtil.getProperties("projectconfig.properties", "GCICAPPSECRET");
                } else if (i == 6) {  //BFCECHeartService  福田康明斯心服务
                    appid = PropertiesUtil.getProperties("projectconfig.properties", "BFCECHeartServiceAPPID");
                    appsecret = PropertiesUtil.getProperties("projectconfig.properties", "BFCECHeartServiceAPPSECRET");
                } else if (i == 7) {  //ACPL  安徽康明斯
                    appid = PropertiesUtil.getProperties("projectconfig.properties", "ACPLAPPID");
                    appsecret = PropertiesUtil.getProperties("projectconfig.properties", "ACPLAPPSECRET");
                }
                //如果获取到的appid或者appsecret为空的就跳过这次循环
                if ("".equals(appid) || "".equals(appsecret) || null == appid || null == appsecret) {
                    continue;
                }
                AccessToken accessToken = WeiXinUtil.getAccessToken(appid, appsecret);
                if (null == accessToken || null == accessToken.getToken()) {
                    /**
                     * 注释log
                     * 20230808
                     * sxt 处理Privacy Violation
                     */
                    //log.error(accessToken);
                    log.error("微信公众号获取token异常，当前服务渠道是:" + i);
                    continue;
                }
                token = accessToken.getToken();  //重新获取的token
                String url = MATERIAL_COUNT.replace("ACCESS_TOKEN", token);//将URL中的token替换掉
                JSONObject materialcountJson = doGetStr(url);
                long companyId = 0;    //企业id    下面做转换
                if (i == 5) {   //广西康明斯  主键id是905
                    companyId = 905;
                } else if (i == 6) {    //BFCECHeartService  福田康明斯心服务   主键id是2
                    companyId = 2;
                } else if (i == 7) {    //ACPL 安徽康明斯   主键id是122
                    companyId = 122;
                } else {
                    companyId = i;
                }
                if (null != materialcountJson.get("news_count")) {
                    //查看本地数据是否存在微信公众号文章(想知道是否下载过)
                    int weChatGetMaterialCount = 0;
                    weChatGetMaterialCount = weChatGetMaterialDao.getWeChatGetMaterialCountByCreatorId(i);
                    if (0 != weChatGetMaterialCount) {
                        //下载过就更新最新的20条文章，没有的就新增，有的就插入
                        //获取当前循环服务渠道的最新20条公众号文章，通过MaterialnMediaId字段比较  相同的就更新对应内容,不同的就插入数据
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("type", "news");
                        jsonObject.put("offset", 0);
                        jsonObject.put("count", 20);
                        String materialListUrl = MATERIAL_List.replace("ACCESS_TOKEN", token);
                        //调用公共方法从微信公众号获取到新闻素材
                        String respones = getMaterialList(materialListUrl, jsonObject);
                        //转成utf-8
                        String data = new String(respones.getBytes("ISO-8859-1"), "utf-8");
                        //循环最新的20条素材    和数据库中的MaterialnMediaId比较   相同的比较
                        List<String> materialnMediaIdList = new ArrayList<>();
                        materialnMediaIdList = weChatGetMaterialDao.getMaterialnMediaIdList(companyId);
                        Map<String, Object> materialMap = JsonUtils.toJavaObject(data, Map.class);
                        if (MapUtils.isNotEmpty(materialMap)) {
                            List<Map<String, Object>> itemMapList = (List) materialMap.get("item");
                            if (CollectionUtils.isNotEmpty(itemMapList)) {
                                for (Map<String, Object> itemMap : itemMapList) {
                                    Map<String, Object> contentMap = (Map<String, Object>) itemMap.get("content");
                                    List<Map<String, Object>> newsItems = (List) contentMap.get("news_item");
                                    for (Map<String, Object> newsItem : newsItems) {
                                        Map<String, Object> MaterialnMap = new HashMap<>();
                                        String materialnMediaId = itemMap.get("media_id").toString();
                                        MaterialnMap.put("MaterialnMediaId", materialnMediaId);
                                        MaterialnMap.put("CompanyId", companyId);
                                        MaterialnMap.put("MaterialnType", "news");
                                        MaterialnMap.put("title", newsItem.get("title"));
                                        MaterialnMap.put("author", newsItem.get("author"));
                                        MaterialnMap.put("digests", newsItem.get("digest"));
                                        MaterialnMap.put("ThumbMediaId", newsItem.get("thumb_media_id"));
                                        MaterialnMap.put("ContentUrl", newsItem.get("url"));
                                        MaterialnMap.put("ThumbUrl", newsItem.get("thumb_url"));
                                        int[] imgWH = ImageUtil.getImgWH(String.valueOf(newsItem.get("thumb_url")));
                                        if (null == imgWH) {
                                            MaterialnMap.put("CoverWidth", 0);    //	封面宽度
                                            MaterialnMap.put("CoverHeight", 0);    //	封面高度
                                        } else {
                                            MaterialnMap.put("CoverWidth", imgWH[0]);    //	封面宽度
                                            MaterialnMap.put("CoverHeight", imgWH[1]);    //	封面高度
                                        }
                                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                        MaterialnMap.put("MaterialnCreateTime", sdf.format(new Date(Long.valueOf(contentMap.get("create_time") + "000"))));
                                        MaterialnMap.put("MaterialnUpdateTime", sdf.format(new Date(Long.valueOf(contentMap.get("update_time") + "000"))));
                                        MaterialnMap.put("Creator", i);
                                        MaterialnMap.put("CreateTime", LocalTimeUtil.getRealCurrentTime());
                                        MaterialnMap.put("Updator", i);
                                        MaterialnMap.put("UpdateTime", LocalTimeUtil.getRealCurrentTime());
                                        if (materialnMediaIdList.contains(materialnMediaId)) {
                                            //存在materialnMediaId就更新
                                            weChatGetMaterialDao.update(MaterialnMap);
                                        } else {
                                            //不存在materialnMediaId就新增
                                            weChatGetMaterialDao.insert(MaterialnMap);
                                        }
                                    }
                                }
                            }
                        }
                    } else {
                        //没下载过，就全量下载文章(一般第一次下载文章到数据库执行此逻辑)
                        int newsCount = materialcountJson.getInt("news_count");  //文章总数
                        int shang = newsCount / 20;  //相差的数(就是新增的数)除于20得出来的商数
                        int yu = newsCount % 20;   //相差的数就是新增的数)除于20得出来得余数
                        //调用公共方法，往数据库导入数据
                        improtData(shang, 20, token, companyId, i);
                        if (yu != 0) {
                            JSONObject jsonObject = new JSONObject();
                            jsonObject.put("type", "news");
                            jsonObject.put("offset", shang * 20);
                            jsonObject.put("count", yu);
                            String materialListUrl = MATERIAL_List.replace("ACCESS_TOKEN", token);
                            //调用公共方法从微信公众号获取到新闻素材
                            String respones = getMaterialList(materialListUrl, jsonObject);
                            //转成utf-8
                            String data = new String(respones.getBytes("ISO-8859-1"), "utf-8");
                            //保存数据库
                            exportSqlServer(data, companyId, i);

                        }
                    }
                } else {
                    log.error(materialcountJson);
                }
            }
		}catch (Exception e){
			log.error("获取微信公众号文章保存数据库定时任务报错："+e.getMessage(), e);
		}finally {
			log.info("定时任务结束----获取微信公众号文章保存数据库");
		}
		System.out.println("同步数据完成");
	}





	//公共方法   把从微信公众号上获取到的素材保存导数据库
	//importNoCount循环次数    素材总数除以每次导入条数  等于循环次数   例如1002除以20=50    循环50次，再循环一次导多余出来的2条
	//importSize每次导入条数   当素材总数大于20，每次导20条   小于20  导素材总数   因为微信公众号每次只能请求20个数据
	//token请求微信公众号所需token
	//companyId服务渠道主键id   CCI,BFCEC,DCEC,XCEC,GCIC  分别为1，2，3，4，905
	public void improtData(int importNoCount,int importSize, String token,long companyId,int creator) throws Exception{
		for(int j=0 ;j<importNoCount ;j++){
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("type","news");
			jsonObject.put("offset",j*20);
			jsonObject.put("count",importSize);
			String materialListUrl = MATERIAL_List.replace("ACCESS_TOKEN",token);
			//调用公共方法从微信公众号获取到新闻素材
			String respones = getMaterialList(materialListUrl,jsonObject);
			//转成utf-8
			String data = new String(respones.getBytes("ISO-8859-1"),"utf-8");
			//保存数据库
			exportSqlServer(data,companyId,creator);
		}
	}

    //公共方法    从微信公众号上获取素材数据
    public String getMaterialList(String materialListUrl,JSONObject jsonObject){
        String respones = HttpUtils.postJson(materialListUrl, JsonUtils.toJsonString(jsonObject), new ResponseHandler<String>() {
            @Override
            public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
                if(response.getStatusLine().getStatusCode() == 200){
                    HttpEntity httpEntity = response.getEntity();
                    return  EntityUtils.toString(httpEntity);
                }
                return null;
            }
        });
        return respones;
    }

	//公共方法，把从微信公众号获取出来的文章素材导入到数据库
	public void exportSqlServer(String data,long companyId,int creator){
		Map<String,Object> materialMap = JsonUtils.toJavaObject(data,Map.class);
		if(MapUtils.isNotEmpty(materialMap)){
			List<Map<String,Object>> itemMapList = (List)materialMap.get("item");
			if(CollectionUtils.isNotEmpty(itemMapList)){
				for(Map<String,Object> itemMap : itemMapList){
					Map<String,Object> contentMap = (Map<String, Object>) itemMap.get("content");
					List<Map<String,Object>> newsItems = (List)contentMap.get("news_item");
					for(Map<String,Object> newsItem : newsItems ){
						Map<String,Object> MaterialnMap = new HashMap<>();
						MaterialnMap.put("CompanyId",companyId);
						MaterialnMap.put("MaterialnType","news");
						MaterialnMap.put("MaterialnMediaId",itemMap.get("media_id"));
						MaterialnMap.put("title",newsItem.get("title"));
						MaterialnMap.put("author",newsItem.get("author"));
						MaterialnMap.put("digests",newsItem.get("digest"));
						MaterialnMap.put("ThumbMediaId",newsItem.get("thumb_media_id"));
						MaterialnMap.put("ContentUrl",newsItem.get("url"));
						MaterialnMap.put("ThumbUrl",newsItem.get("thumb_url"));
						SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
						MaterialnMap.put("MaterialnCreateTime",sdf.format(new Date(Long.valueOf(contentMap.get("create_time")+"000"))));
						MaterialnMap.put("MaterialnUpdateTime",sdf.format(new Date(Long.valueOf(contentMap.get("update_time")+"000"))));
						MaterialnMap.put("Creator",creator);
						MaterialnMap.put("CreateTime", LocalTimeUtil.getRealCurrentTime());
						weChatGetMaterialDao.insert(MaterialnMap);
					}
				}
			}
		}
	}




}
